//created by kael 2025.07.21
//modified by kael 2025.07.21

//Write logs to the specified file (source)

#include "plog.h"

// 全局互斥锁 此翻译单元可见
static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;

// 日志函数
void logToFile(const char* filename, LogToFile_Level level, const char* format, ...) {
    // 加锁
    pthread_mutex_lock(&log_mutex);

    // 生成日期后缀（如 "server_log_20231005.txt"）
    time_t now = time(NULL);
    struct tm* tm_info = localtime(&now);
    char dated_filename[256] = {0};
    char date_str[20] = {0};
    strftime(date_str, sizeof(date_str), "%Y%m%d", tm_info);
    sprintf(dated_filename, "%s_%s", filename, date_str);  // 拼接文件名


    FILE* file = fopen(dated_filename, "a");  // 使用带日期的文件名 追加模式打开文件
    if (!file) {
        perror("Failed to open log file");
        pthread_mutex_unlock(&log_mutex);  // 解锁
        return;
    }

    // 获取当前时间
    now = time(NULL);
    tm_info = localtime(&now);
    char time_str[20] = {0};
    strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", tm_info);

    // 日志级别字符串
    const char* level_str = "";
    switch (level) {
        case LOGTOFILE_DEBUG:   level_str = "DEBUG"; break;
        case LOGTOFILE_INFO:    level_str = "INFO"; break;
        case LOGTOFILE_WARNING: level_str = "WARN"; break;
        case LOGTOFILE_ERROR:   level_str = "ERROR"; break;
    }

    // 写入时间、级别
    fprintf(file, "[%s] [%s] ", time_str, level_str);

    // 写入用户日志内容
    va_list args;
    va_start(args, format);
    vfprintf(file, format, args);
    va_end(args);

    //输出换行
    fprintf(file, "\n");
    fclose(file);

    // 解锁
    pthread_mutex_unlock(&log_mutex);
}



